import { useRef, useState } from 'react';
import TButton from '../TButton';

import './index.less';

interface IProps {
  defaultFields: Record<string, any>;
  mainField: string;
  onCreate: (values: Record<string, any>) => void;
  placeholder?: string;
}

const QuickCreator = (props: IProps) => {
  const { defaultFields, mainField, onCreate, placeholder = '' } = props;
  const [value, setValue] = useState('');
  const [focus, setFocus] = useState(false);
  const inputRef = useRef<HTMLInputElement | null>(null)

  const quickCreate = () => {
    if (!value || !value.trim()) {
      return
    }
    onCreate({
      [mainField]: value,
      ...JSON.parse(JSON.stringify(defaultFields)),
    });
    setValue('')
    if (inputRef.current) {
      inputRef.current.blur()
    }
  };
  return (
    <div className={['quick-creator', focus ? 'quick-creator--focus' : '' ].join(' ')}>
      <input
        ref={inputRef}
        value={value}
        onChange={(e) => setValue(e.target.value)}
        onKeyDown={(e) => {
          if (e.keyCode === 13) {
            quickCreate();
          }
        }}
        
        placeholder={placeholder}
        onFocus={() => setFocus(true)}
        onBlur={() => setFocus(false)}
      />
      <TButton
        style={{
          width: '40px',
          height: '20px',
          position: 'absolute',
          right: '4px',
        }}
        onClick={quickCreate}
      >
        +
      </TButton>
    </div>
  );
};

export default QuickCreator;
